import os
import hashlib
import binascii
import random
import json


def load_json_file(path):
    """加载json文件"""
    file = open(path, "r")
    try:
        json_str = json.loads(file.read())
        return json_str
    except Exception as e:
        print("load json file failed: ", path, str(e))


def is_file(real_path):
    """
    32768 is file
    """
    try:
        stat = os.stat(real_path)
        if stat[0] == 32768:
            return True
        return False
    except Exception as e:
        return False


def is_dir(real_path):
    """
    16384 is dir
    """
    try:
        stat = os.stat(real_path)
        if stat[0] == 16384:
            return True
        return False
    except Exception as e:
        return False


def get_file_size(real_path):
    """
    size Kb
    error return -1
    """
    try:
        if is_file(real_path):
            stat = os.stat(real_path)
            return stat[6]
        return -1
    except Exception as e:
        return -1


def get_file_info(real_path):
    """
    error return {}
    """
    info = {"size": -1, "ext": ""}
    try:
        if is_file(real_path):
            stat = os.stat(real_path)
            info["path"] = real_path
            info["size"] = stat[6]
            info["ext"] = get_file_ext(real_path)
            info["mime"] = get_ext_mime(info["ext"])
            info["etag"] = get_file_md5(real_path)
        return info
    except Exception as e:
        print(f"file {real_path} read info failed", e)
        return info


def get_file_ext(real_path):
    if is_file(real_path):
        parts = real_path.split(".")
        return parts[-1]
    return None


def get_file_md5(real_path):
    md5_v = str(random.randrange(1000, 10000))
    try:
        if is_file(real_path):
            with open(real_path, "rb") as f:
                v = hashlib.md5(f.read(50)).digest()
                md5_v = binascii.hexlify(v).decode("ascii")
    except Exception as e:
        print("get md5 error", e)
    return md5_v


def get_ext_mime(ext):
    mimes = {
        "log": "text/plain",
        "jfif": "image/pipeg",
        "wma": "audio/x-ms-wma",
        "rar": "application/vnd.rar",
        "avif": "image/avif",
        "mjs": "text/javascript",
        "midi": "audio/midi",
        "mid": "audio/midi",
        "md": "text/markdown",
        "weba": "audio/webm",
        "woff2": "font/woff2",
        "woff": "font/woff",
        "xls": "application/vnd.ms-excel",
        "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "epub": "application/epub+zip",
        "php": "application/x-httpd-php",
        "ppt": "application/vnd.ms-powerpoint",
        "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
        "tar": "application/x-tar",
        "zip": "application/zip",
        "xml": "application/xml",
        "webm": "video/webm",
        "wav": "audio/wav",
        "ttf": "font/ttf",
        "rar": "application/vnd.rar",
        "pdf": "application/pdf",
        "mpeg": "video/mpeg",
        "mp4": "video/mp4",
        "mp3": "audio/mpeg",
        "json": "application/json",
        "js": "text/javascript",
        "htm": "text/html",
        "html": "text/html",
        "txt": "text/plain",
        "png": "image/png",
        "jpg": "image/jpeg",
        "jpeg": "image/jpeg",
        "webp": "image/webp",
        "svg": "image/svg+xml",
        "gif": "image/gif",
        "aac": "audio/aac",
        "avi": "video/x-msvideo",
        "bin": "application/octet-stream",
        "bmp": "image/bmp",
        "css": "text/css",
        "csv": "text/csv",
        "doc": "application/msword",
        "gz": "application/gzip",
        "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "unknown": "application/octet-stream",
    }

    if ext in mimes:
        return mimes[ext]
    return mimes["unknown"]


def copy_file(src_path, target_path):
    """复制文件"""
    with open(src_path, "rb") as src:
        with open(target_path, "wb") as target:
            while True:
                data = src.read(512)
                if not data:
                    break
                target.write(data)


if __name__ == "__main__":
    print(is_file("/config"))
    print(is_dir("/config"))
    print(is_file("/main.py"))
    print(is_dir("/main.py"))
    print(get_file_info("/main.py"))
